<template>
  <div class="container">
    <a-modal v-model:visible="visible" title="台词配音" @cancel="handleCancel" width="500px" centered>
      <div style="border: 1px solid #ccc" class="editor-box">
        <a-textarea style="height: 100%; width: 100%" placeholder="输入台词配音" :bordered="false" class="no-resize textarea"
          :maxlength="100" v-model:value="audioText" @change="audioTextChange" />
      </div>
      <!-- 开始时间 -->
      <div class="startTime flex mTop">
        <span class="startTime-left label">开始时间</span>
        <a-input-number style="width: 100px" :rules="customRules" addon-after="秒" :step="0.1" :min="0"
          v-model:value="start_time" />
      </div>
      <!-- 音色选择 -->
      <div class="tone-select flex mTop">
        <div class="tone-select-left label mRg-10px">音色选择</div>
        <div class="tone-select-right flex border">
          <!-- 音色头像 -->
          <div class="tone-avatar">
            <img :src="script_scenes.audio_config.img" alt="" />
            <strong class="tone-name">{{
              script_scenes.audio_config.name
            }}</strong>
          </div>
          <!-- 操作按钮 -->
          <div class="operate flex">
            <!-- 替换选择 -->
            <a-spin :spinning="false">
              <span class="swap-icon" @click="scriptAudioSelectionShowModal()"><swap-outlined style="font-size: 14px" />
                替换</span>
            </a-spin>
            <!-- 音频播放器 -->
            <audio @ended="handleAudioEnded" ref="audioRef" :src="script_scenes.audio_config.audio_url"
              style="display: none"></audio>

            <a-spin :spinning="isSpining">
              <!-- 暂停按钮 -->
              <span class="play-icon" v-if="isPlaying" @click="pauseAudioHandle()">
                <pause-outlined />
                暂停
              </span>
              <!-- 播放按钮 -->
              <span class="play-icon" v-else @click="playAudioHandle()">
                <caret-right-outlined />试听
              </span>
            </a-spin>
          </div>
        </div>
      </div>
      <!-- 配音音量 -->
      <div class="dubbing-volume mTop flex">
        <div class="dubbing-volume-left label mRg-20px">配音音量</div>
        <div class="dubbing-volume-right">
          <span class="min-volume">1</span>
          <a-slider :min="1" :max="11" class="volume-slider" @change="changeVolume" v-model:value="volume" />
          <span class="max-volume"> 11</span>
        </div>
      </div>
      <div class="all-applicat flex mTop">
        <div class="all-applicat-left label mRg-20px">应用全部</div>
        <div class="all-applicat-right">
          <a-switch v-model:checked="open_global"></a-switch>
        </div>
      </div>
      <!-- 底部操作样式 -->
      <template #footer>
        <a-button key="back" @click="deletHandle">删除配音</a-button>
        <a-button key="submit" type="primary" @click="handleOk">确定</a-button>
      </template>
    </a-modal>
    <ScriptAudioSelection ref="scriptAudioSelection" :audioConfig="audioConfig"
      @closeAudioSelection="closeAudioSelection">
    </ScriptAudioSelection>
  </div>
</template>
<script>
import {
  defineComponent,
  reactive,
  toRefs,
  onMounted,
  ref,
  watch,
  nextTick,
  createVNode,
} from "vue";
import {
  SwapOutlined,
  ClockCircleOutlined,
  CaretRightOutlined,
  PauseOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons-vue";
// 音色选中组件
import ScriptAudioSelection from "./ScriptAudioSelection.vue";
import request from "@/common/utils/request";
import { message, Modal } from "ant-design-vue";
import _ from "lodash";
export default defineComponent({
  components: {
    SwapOutlined,
    ClockCircleOutlined,
    CaretRightOutlined,
    PauseOutlined,
    ScriptAudioSelection,
    ExclamationCircleOutlined,
  },

  setup(props, context) {
    const state = reactive({
      visible: false, //控制页面弹窗打开
      script_scenes: {}, //单个音频配置数据
      isResultUrl: "", //播放文案地址
      isPlaying: false, //播放状态
      isSpining: false, //spin加载
      start_time: 0, //开始时间
      open_global: false, //是否应用全部
      volume: 0, //音频音量
      audioText: "",
    });
    // 弹窗开启
    const showModal = (info, indexKey) => {
      console.log(info);
      //初始化音频配置
      state.script_scenes = {
        ...JSON.parse(JSON.stringify(info)),
        audio_config: {
          ...info.audio_config,
        },
      };
      state.start_time = state.script_scenes.audio_config.start_time / 1000; //初始化要将毫秒转换成秒
      state.open_global = state.script_scenes.audio_config.open_global; //初始化是否应用全部
      state.volume = state.script_scenes.audio_config.volume + 1; //初始化需要+1
      state.audioText = state.script_scenes.line_audio[0].elements[0][0].text;
      state.visible = true; //打开弹窗
      isAudioConfigChange.value = true;
      TextAreaChange.value = true;
    };
    // 判断配置项是否改变
    let isAudioConfigChange = ref(true);
    // 音色选择弹窗组件
    const scriptAudioSelection = ref(null); //默认没有改变
    // 打开音色选择弹窗
    const scriptAudioSelectionShowModal = () => {
      pauseAudioHandle();
      scriptAudioSelection.value.showModal({
        ...state.script_scenes.audio_config,
        volume: state.volume,
      });
      console.log(state.volume);
    };
    // 音色弹窗选中成功成功回调，接收传值
    const closeAudioSelection = (info) => {
      // 判断数据是否改变了
      isAudioConfigChange.value = _.isEqual(info, {
        ...state.script_scenes.audio_config,
        volume: state.volume,
      });
      state.script_scenes.audio_config = {
        ...state.script_scenes.audio_config,
        ...info,
      };
      state.volume = info.volume;
    };
    // 删除音频
    const deletHandle = () => {
      Modal.confirm({
        title: () => `确定删除配音吗?`,
        content: "",
        okText: "确认",
        cancelText: "取消",
        icon: () => createVNode(ExclamationCircleOutlined),
        centered: true,
        onOk() {
          context.emit("deleteLineAudio");
          // 确定删除吗
          state.visible = false;
        },
        onCancel: () => {
          console.log("Cancel");
        },
      });
    };
    const audioRef = ref(null); //音频播放实例
    // 音频试听
    const playAudioHandle = () => {
      // 关闭正在播放的音频
      pauseAudioHandle();
      // 数据无变化
      if (isAudioConfigChange.value) {
        state.isPlaying = !state.isPlaying;
        nextTick(() => {
          audioRef.value && audioRef.value.play();
        });
        return;
      } else {
        // 数据变化
        state.isSpining = true; //开启加载
      }

      request
        .get("/work_ai", "/user/shotstack/textToVoice", {
          ...state.audioConfig,
          timbre_id: state.script_scenes.audio_config.voice_type,
          text: "智能配音是一种利用人工智能技术实现的语音合成功能，它可以将文本内容转换成逼真的人类语音",
        })
        .then((res) => {
          let tiem = setInterval(() => {
            request
              .get("/work_ai", "/user/shotstack/getVoice", {
                task_id: res.result.task_id,
                request_id: res.result.request_id || ''
              })
              .then((task) => {
                if (task.result.Data.ResultUrl) {
                  state.script_scenes.audio_config.audio_url =
                    task.result.Data.ResultUrl;
                       state.script_scenes.audio_config.media_id =
                   task.result.Data?.media_id ||'';
                  state.isSpining = false;
                  state.isPlaying = true;
                  nextTick(() => {
                    audioRef.value && audioRef.value.play();
                  });
                  console.log(audioRef.value);
                  clearInterval(tiem);
                }
              })
              .catch((err) => {
                console.log(err);
              })
              .finally(() => {
                state.isSpining = false; //关闭spin加载
                state.isPlaying = true; //播放状态为暂停
                clearInterval(tiem);
              });
          }, 1000);
        });
    };
    // 音频播放完成
    const handleAudioEnded = () => {
      audioRef.value.currentTime = 0;
      state.isPlaying = false;
    };
    // 暂停播放音频
    const pauseAudioHandle = () => {
      state.isPlaying = false;
      audioRef.value && audioRef.value.pause();
    };
    const handleCancel = () => {
      state.isShowModal = false;
      audioRef.value.currentTime = 0;
      pauseAudioHandle();
    };
    // 弹窗关闭
    const handleOk = () => {
      if (state.audioText.trim().length < 1) {
        return message.error("请填写文案");
      }
      let paramsObj = {
        ...state.script_scenes,
        audio_config: {
          ...state.script_scenes.audio_config,
          volume: state.volume - 1, //展示为+1操作，提交给后端是-1操作
          start_time: state.start_time * 1000, //提交时候需要将秒转换成毫秒
          open_global: state.open_global,
        },

        isChange: isAudioConfigChange.value, //判断是否改变
        TextAreaChange: TextAreaChange.value,
      };
      paramsObj.line_audio[0].elements[0][0].text = state.audioText;
      console.log(paramsObj, "oiwiwowo");
      context.emit("closeDubbing", paramsObj); //传值给父组件
      state.visible = false;
    };
    // 监听音量变化
    const changeVolume = (val) => {
      pauseAudioHandle();
      isAudioConfigChange.value =
        // state.script_scenes.audio_config.volume == val;
        isAudioConfigChange.value =
        state.script_scenes.audio_config.volume == val - 1 ? true : false;
      console.log(val - 1, state.script_scenes.audio_config.volume);
      console.log(isAudioConfigChange.value, "监听音色是否改变");
    };
    const TextAreaChange = ref(true);
    // 监听文本变化
    const audioTextChange = () => {
      TextAreaChange.value =
        state.script_scenes.line_audio[0].elements[0][0].text ===
          state.audioText
          ? true
          : false;
      console.log(TextAreaChange.value, "监听文本是否改变");
    };
    // 监听时间变化
    return {
      ...toRefs(state),
      showModal,
      handleOk,
      scriptAudioSelection,
      closeAudioSelection,
      deletHandle,
      playAudioHandle,
      pauseAudioHandle,
      handleAudioEnded,
      audioRef,
      handleCancel,
      isAudioConfigChange,
      scriptAudioSelectionShowModal,
      changeVolume,
      audioTextChange,
      TextAreaChange,
    };
  },
});
</script>
<style lang="less" scoped>
.label {
  color: #737a87;
  font-weight: 600;
}

.flex {
  display: flex;
  align-items: center;
}

.border {
  border: 1px solid #ebeef2;
}

.mTop {
  margin-top: 15px;
}

.mRg-10px {
  margin-right: 10px;
}

.pointer {
  cursor: pointer;
}

.secends {
  height: 40px;
  line-height: 40px;
  padding: 0 10px;

  &:hover {
    background: #f4f5f5;
  }
}

.header {
  justify-content: space-between;

  .header-right {
    flex: 1;
    justify-content: flex-end;

    span {
      background: #f4f5f5;
      border-radius: 5px;
      padding: 2px 5px;
      display: flex;
      font-size: 12px;
      align-items: center;
    }

    :deep(.ant-popover-inner-content) {
      .insert-card {
        p {
          color: #009589;
          background: skyblue !important;
        }
      }
    }
  }
}

// 输入框
.editor-box {
  margin: 10px 0;
  height: 100px;
}

// 开始时间
.startTime {
  height: 30px;

  .startTime-left {
    margin-right: 10px;
  }
}

// 音色选择
.tone-select {
  .tone-select-right {
    height: 80px;
    flex: 1;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 10px;

    // 头像
    img {
      width: 60px;
      height: 60px;
      border-radius: 50%;
      margin-right: 10px;
    }

    // 操作按钮
    .operate {
      color: #838a95;
      cursor: pointer; //输入移入显示小手

      .swap-icon,
      .play-icon {
        border: 1px solid #ebeef2;
        padding: 5px 10px;
        font-size: 14px;
      }

      .swap-icon {
        margin-right: 5px;
      }
    }
  }
}

// 配音音量
.dubbing-volume {
  .dubbing-volume-left {
    margin-right: 10px;
  }

  .dubbing-volume-right {
    flex: 1;
    display: flex;
    align-items: center;
    height: 30px;

    .min-volume,
    .max-volume {
      width: 20px;
      height: 100%;
      display: flex;
      align-items: center;
      margin: 0 5px;
    }

    .volume-slider {
      flex: 1;
    }
  }
}

// 应用全部
.all-applicat {
  .all-applicat-left {
    margin-right: 10px;
  }
}

:deep(.ss-form-item) {
  margin-bottom: 0;
}

// 禁用输入框拖拽功能
.no-resize {
  resize: none;
}

.textarea {
  &::-webkit-scrollbar {
    display: none;
  }

  &::-webkit-scrollbar-track {
    width: 5px;
    background-color: transparent;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
  }

  &::-webkit-scrollbar-thumb {
    background-color: rgba(193, 193, 193, 0.5);
    background-clip: padding-box;
    min-height: 28px;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
  }
}
</style>
